package com.wxb.qd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxb.qd.common.ErrorCode;
import com.wxb.qd.common.UserConstant;
import com.wxb.qd.common.UserCount;
import com.wxb.qd.entity.User;
import com.wxb.qd.exception.BusinessException;
import com.wxb.qd.mapper.UserMapper;
import com.wxb.qd.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
* @author 12796
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-03-03 16:31:54
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String ,Object> redisTemplate;


    /**
     * 用户注册方法
     * @param userAccount 用户账号
     * @param userPassword 用户密码
     * @param checkPassword 二次确认密码
     * @return 新建的用户id
     */
    @Override
    public int userRegister(String userAccount, String userPassword, String checkPassword) {
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"输入有空");
        }
        if (userAccount.length() < 3){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号大于等于3");
        }
        if (userPassword.length() < 6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码大于等于6");
        }
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"第二次输入的密码和之前不一样");
        }

        //查找到有这个账号的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(userPassword);
        user.setCreateTime(new Date());
        user.setIsDelete(0);
        user.setIsAdmin(UserConstant.NOT_ADMIN);
        user.setUserAvatar("https://xsgames.co/randomusers/avatar.php?g=pixel&key=1");
        boolean saveUser = this.save(user);
        if (!saveUser){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败，数据库出错");
        }
        return user.getId();
    }

    /**
     * 用户登录
     * @param userAccount 用户账号
     * @param userPassword 用户密码
     * @param request 请求，用于设置用户的登录态
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"输入有空");
        }
        if (userAccount.length() < 3){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号大于等于3");
        }
        if (userPassword.length() < 6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码大于等于6");
        }
        //查找用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",userPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户不存在或者密码错误");
        }
        if (user.getIsDelete() == 1){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户已经被废弃");
        }
        //记录用户的登录态即可
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,user);
        return user;
    }

    /**
     * 获取当前用户
     * @param request 请求
     * @return 当前用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getId() == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"用户未登录");
        }
        return user;
    }

    @Override
    public List<UserCount> getAllUserAndHasAeroData() {
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        String key = "wxb:qd:counts";
        Object o = operations.get(key);
        if (o == null){
            List<UserCount> counts = userMapper.getCounts();
            operations.set(key,counts);
            return counts;
        }
        ObjectMapper objectMapper = new ObjectMapper();

        return (List<UserCount>) o;
    }

    /**
     * 用户退出,删除用户的登录态，
     * @param request 请求
     * @return 删除成功
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"用户未登录");
        }
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }
}




